/*
 * Copyright 2014 Christian Hildebrandt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.sisoft.timera.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.apache.log4j.Logger;

import de.sisoft.timera.literal.Constants;

/**
 *
 * @author Men@Work
 */
public class BaseDao {

    protected static final Logger LOG = Logger.getLogger("timemanagementbackend.dao");

    private static final EntityManagerFactory emf = javax.persistence.Persistence
	    .createEntityManagerFactory(Constants.Database.PERSISTENCE_UNIT);

    protected EntityManager getEntityManager() {
	return emf.createEntityManager();
    }

    protected Object createOrUpdate(final Object object) {
	final EntityManager em = getEntityManager();
	em.getTransaction().begin();
	try {
	    em.persist(em.contains(object) ? object : em.merge(object));
	    em.getTransaction().commit();
	    LOG.debug("Persisted " + object);
	} catch (final Exception e) {
	    LOG.error("Could not persist Object", e);
	    em.getTransaction().rollback();
	} finally {
	    em.close();
	}
	return object;
    }

    public Object read(final Object object) {
	final EntityManager em = getEntityManager();
	Object result = null;
	em.getTransaction().begin();
	try {
	    result = em.find(object.getClass(), object);
	    LOG.debug("Found " + object);
	} catch (final Exception e) {
	    LOG.error("Could not find Object", e);
	} finally {
	    em.close();
	}
	return result;
    }

    protected void update(final Object object) {
	final EntityManager em = getEntityManager();
	em.getTransaction().begin();
	try {
	    em.merge(object);
	    em.getTransaction().commit();
	} catch (final Exception e) {
	    LOG.error("Could not update Object", e);
	    em.getTransaction().rollback();
	} finally {
	    em.close();
	}
    }

    protected void delete(final Object object) {
	final EntityManager em = getEntityManager();
	em.getTransaction().begin();
	try {
	    em.remove(em.contains(object) ? object : em.merge(object));
	    em.getTransaction().commit();
	} catch (final Exception e) {
	    LOG.error("Could not delete Object", e);
	    em.getTransaction().rollback();
	} finally {
	    em.close();
	}
    }

}
